<!-- 购物车组件 -->
<template>
	<view class="cart-center">
		<!-- 步骤导航 -->
		<view class="top-nav">
			<view class="cart-icon">
				<!-- <image src="/static/carousel04.png" mode="aspectFill"></image> -->
				<!-- <text class="iconfont icon-gouwuche icon-gouwucheColor"></text>
				<text>付款</text> -->
			</view>
			<view class="step-bar">
				<view class="step-item active">1. 查看购物车</view>
				<view class="step-item">2. 填写订单</view>
				<view class="step-item">3. 付款，完成购买</view>
			</view>
		</view>

		<!-- 购物车列表区域 -->
		<view class="cart-container">
			<uni-table ref="table" border stripe type="selection" emptyText="购物车暂无内容，快去加入商品吧"
				@selection-change="handleAllCheck">

				<uni-tr>
					<uni-th width="260" align="center">商品</uni-th>
					<uni-th width="160" align="center">单价</uni-th>
					<uni-th width="160" align="center">数量</uni-th>
					<uni-th width="160" align="center">小计</uni-th>
					<uni-th width="100" align="center">操作</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in cartList" :key="index" v-if="cartList.length>0">
					<uni-td align="center">
						<view class="information">
							<view class="td-img">
								<image :src="item.param.image" mode="aspectFill"></image>
							</view>
							<view class="introduce">
								<view class="introduce-name">{{item.goods_title}}</view>
								<view class="introduce-model">{{item.param.model}}{{item.param.specs}}</view>
							</view>
						</view>
					</uni-td>
					<uni-td align="center">
						<view class="item-price">¥{{ (item.param.price-0).toFixed(2) }}</view>
					</uni-td>
					<uni-td align="center">
						<view class="item-count">
							<button class="count-btn" @click="handleMinus(item,index)"
								:disabled="item.param.number <= 1">-</button>
							<input class="count-input" type="number" maxlength="4" v-model="item.param.number"
								@blur="handleCountChange(item, index)" />
							<button class="count-btn" :disabled="item.param.number>=9999"
								@click="handlePlus(item,index)">+</button>
						</view>
					</uni-td>
					<uni-td align="center">
						<!-- 商品小计 -->
						<view class="item-subtotal">¥{{ (item.param.price * item.param.number).toFixed(2) }}</view>
					</uni-td>
					<uni-td>
						<view class="uni-group">
							<button class="uni-button" @click="handleDelete(item,index)" size="mini">删除</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
			<!-- 底部操作栏 -->
			<view class="cart-footer">
				<view class="selected-info">
					已选商品 {{ selectedCount }} 件
					<button class="clear-btn" :disabled="cartList.length<=0" @click="clearCart">清空购物车</button>
				</view>
				<view class="total-settlement">
					<view class="total-price">总价：¥{{ totalPrice.toFixed(2) }}</view>
					<button class="settle-btn" :disabled="cartSelectedList.length<1" @click="settle">结算</button>
				</view>

			</view>
		</view>
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="info" cancelText="取消" confirmText="确认" title="提示" content="确认删除此商品？"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		cart,
		cartClear,
		cartNumber
	} from '../../utils/http_data.js';

	import cartUtil from '../../common/cart.js';
	export default {
		name: "shoppingCart",
		data() {
			return {
				currentStep: 0, // 当前步骤，0：查看购物车；1：填写订单；2：付款完成
				itemLiIndex: -1, // 要删除的商品索引，初始为-1
				cartList: [
					// 	{
					// 	image: '/static/images/pwm_controller.png', // 替换为实际图片路径，可放 static 目录
					// 	crate_date: "2025-08-14T03:41:39.296Z",
					// 	goods_id: "68944f99ce5ec9e58d3aa855",
					// 	goods_title: "中文名称",
					// 	goods_image: "https://mp-5a81006c-e233-49f0-8a6a-cb59bcd34a71.cdn.bspapp.com/cloudstorage/7d585860-550f-4fb7-a75c-d4c99889cc92.png",
					// 	param: {
					// 		delivery_date: "一周内",
					// 		model: "中文模型",
					// 		number: 0,
					// 		price: "200",
					// 		serial_number: "123123123",
					// 		specs: "中文规格",
					// 		total_price: 5400,
					// 	}
					// },
				],
				cartLi: {},
				cartSelectedList: [], // 选中的数组
				selIndex: [], // 删除后需要选中的
			};
		},
		computed: {
			// 已选商品数量
			selectedCount() {
				// return this.cartList.filter(item => item.checked).length; // 按照商品计算
				return this.cartList.reduce((total, item) => { // 按照商品数量计算
					return item.checked ? total + item.param.number : total;
				}, 0);
			},
			// 总价计算
			totalPrice() {
				return this.cartList.reduce((total, item) => {
					return item.checked ? total + item.param.price * item.param.number : total;
				}, 0);
			}
		},
		mounted() {
			this.cartFun();
		},
		methods: {
			// 获取购物车数据
			cartFun() {
				const uid = uni.getStorageSync('login-userinfo')._id
				cart(uid).then((data) => {
					this.cartList = data.data;
					cartNumber(uid).then((data) => {
						this.$emit('cartTotalN', data.totalN)
					})
					if (this.cartList.length > 0) {

						this.$nextTick(() => {
							this.$refs.table.selectionAll() // 选中全部
						});
					}

				})
			},

			// 确认删除
			dialogConfirm() {
				this.typeToCart('remove', this.cartLi, this.cartLi.param.number).then(() => {
					this.cartList.splice(this.itemLiIndex, 1);

					this.$refs.table.clearSelection(); // 先清空所有选中
					this.$refs.table.toggleRowSelection(this.selIndex, true) // 用于多选表格，切换某一行的选中状态
					
					this.$refs.alertDialog.close()
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
					cartNumber(uid).then((data) => { // 获取购物车长度
						this.$emit('cartTotalN', data.totalN)
					})
				}).catch(() => {

				})
			},
			//删除关闭
			dialogClose() {
				this.$refs.alertDialog.close()
			},

			// 多选处理
			selectedItems() {
				return this.selectedIndexs.map(i => this.cartList[i])
			},
			aaa(e) {
				
			},
			// 全选/全不选逻辑
			handleAllCheck(e) {
				
				this.selectedIndexs = e.detail.index
				this.cartSelectedList = [];
				this.cartList.forEach((item, index) => {
					if (this.selectedIndexs.includes(index)) {
						item.checked = true;
						this.cartSelectedList.push(item);
					} else {
						item.checked = false;
					}
				});
			},
			// 增加数量
			handlePlus(item, index) {
				item.param.number++;
				const itemIndex = this.cartSelectedList.findIndex(cartItem => cartItem._id === item._id);
				if (itemIndex !== -1) {
					// 如果存在则替换原元素
					this.cartSelectedList[itemIndex].param.total_price = item.param.number * item.param.price;
				}
				this.typeToCart('update', item, item.param.number)
			},
			// 减少数量
			handleMinus(item, index) {
				// cartSelectedList
				if (item.param.number > 1) {
					item.param.number--;

					const itemIndex = this.cartSelectedList.findIndex(cartItem => cartItem._id === item._id);
					
					if (itemIndex !== -1) {
						// 如果存在则替换原元素
						this.cartSelectedList[itemIndex].param.total_price = item.param.number * item.param.price;
					}

					
					this.typeToCart('update', item, item.param.number)
				}
			},
			// 数量输入框改变
			handleCountChange(item, index) {
				
				const val = item.param.number;
				if (val && val > 0) {
					
					item.param.number = parseInt(val);
				} else {
					
					item.param.number = 1;
					
				}
				const itemIndex = this.cartSelectedList.findIndex(cartItem => cartItem._id === item._id);
				if (itemIndex !== -1) {
					// 如果存在则替换原元素
					this.cartSelectedList[itemIndex].param.total_price = item.param.number * item.param.price;
				}
				this.typeToCart('update', item, item.param.number)
			},
			// 删除商品
			handleDelete(item, index) {
				this.$refs.alertDialog.open() // 打开二次确认弹窗
				
				this.itemLiIndex = index; // 记录当前点击的索引
				this.cartLi = item; // 记录当前点击的元素

				this.selIndex = this.processArray(this.selectedIndexs, index)
				
			},
			processArray(arr, num) {
				let newArr = [...arr];
				newArr = newArr.filter(item => item !== num); //删除所有等于num的元素
				newArr = newArr.map(item => item > num ? item - 1 : item); //所有大于num的元素减1（补位）
				return newArr;
			},
			// 清空购物车
			async clearCart() {
				uni.showLoading({
					title: '清空中...'
				});

				const uid = uni.getStorageSync('login-userinfo')._id
				cartClear(uid).then((res) => {
				

					this.$refs.table.clearSelection() // 清空
					uni.hideLoading();
					
					this.cartList = [];
					this.cartSelectedList = [];
					this.selectedItems()
				}).catch((err) => {
					console.log('失败', err)
				})
			},
			// 更新类型 数量增加更新  减少  删除
			async typeToCart(type, item, quantity) {
				
				uni.showLoading({
					title: '处理中...'
				});

				const uid = uni.getStorageSync('login-userinfo')._id
				const totalCount = await cartUtil.updateToCart({
					_id: item._id,
					quantity: quantity
				}, type, uid)
				uni.hideLoading();
				this.$emit('cartTotalN', totalCount.totalN)

				return new Promise((resolve, reject) => {
					resolve()
				})

			},
			// 结算逻辑（可根据步骤跳转不同页面）
			settle() {
				
				if (this.cartSelectedList.length < 1) {
					uni.showToast({
						title: '请选择商品结算'
					})
				}
				this.currentStep = 1;
				
				const transmit = {
					cartList: this.cartSelectedList,
					totalPrice: this.totalPrice.toFixed(2),
					currentStep: this.currentStep,
					number: this.selectedCount
				}
				

				

				uni.setStorage({
					key: 'transmit',
					data: transmit,
					success: function() {
						uni.redirectTo({
							url: '/pages/shopping_confirm/shopping_confirm'
						});
					}
				});


			},
		}
	}
</script>

<style scoped>
	.cart-center {
		max-width: 1600px;
		min-width: 1280px;
		height: 800px;
		margin: 20px auto;
		background-color: #fff;
	}

	/* 步骤条样式 */
	.top-nav {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.cart-icon {
		display: flex;
		align-items: center;
	}

	.cart-icon image {
		width: 20px;
		height: 20px;
		margin-right: 10px;
	}

	.step-bar {
		display: flex;
	}

	.step-item {
		padding: 5px 10px;
		background-color: #f0f0f0;
		border-radius: 5px;
		margin-right: 10px;
	}

	.active {
		background-color: #f54242;
		color: #fff;
	}


	/* 购物车容器样式 */
	.cart-container {
		padding: 10px;
	}

	.cart-container /deep/ .table--border {
		min-height: 650px;
	}

	.border-none {
		height: 640px;
		overflow-y: auto;
	}

	.uni-table-loading {
		height: 600px;
		line-height: 240px;
	}

	.information {
		display: flex;
		border-bottom: 1px #EBEEF5 solid;
		padding: 8px 10px;
	}

	.information:last-child {
		border-bottom: 0 #EBEEF5 solid;
	}

	.introduce {
		width: 326px;
		text-align: left;
		/* margin-left: 30px; */
	}

	.introduce-name {}

	.introduce-model {
		padding-top: 20px;
	}

	.td-img {
		width: 100px;
		height: 100px;
		margin: auto;
		margin-right: 26px;
	}

	.td-img image {
		width: 100%;
		height: 100%;
	}


	.count-btn {
		width: 30px;
		height: 30px;
		line-height: 30px;
		text-align: center;
		padding: 0;
		margin: 0 5px;
	}

	.count-input {
		width: 40px;
		height: 30px;
		text-align: center;
		border: 1px solid #ccc;
	}

	.delete-btn {
		background-color: #f4f4f4;
		color: #333;
	}


	.item-price,
	.item-subtotal {
		width: 80px;
		text-align: center;
		color: #e60012;
		margin: 0 auto;
	}

	.item-count {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 120px;
		margin: 0 auto;
	}

	/* 底部操作栏样式 */
	.cart-footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px;
		background-color: #f5f5f5;
		border: 1px solid #eee;
		margin-top: 10px;
	}

	.selected-info {
		display: flex;
		align-items: center;
		max-width: 1280px;
		min-width: 800px;
	}

	.clear-btn {
		width: 100px;
		height: 40px;
		margin-left: 10px;
		font-size: 14px;
		line-height: 40px;
		background-color: #fff;
		color: #333;
	}

	.total-settlement {
		width: 240px;
		float: right;
		display: flex;
		align-items: center;
	}

	.total-price {
		font-weight: bold;
		color: #e60012;
	}

	.settle-btn {
		width: 100px;
		background-color: #e60012;
		color: #fff;
	}

	.cart-center /deep/ .uni-dialog-button {
		cursor: pointer;
	}
</style>